package com.example.gustavo.hello.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.TextUtils;
import android.widget.ImageView;

import com.google.gson.Gson;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.BinaryHttpResponseHandler;
import com.loopj.android.http.ResponseHandlerInterface;

import org.apache.http.Header;
import org.apache.http.client.ResponseHandler;

/**
 * Created by gustavo on 2015/2/25.
 */
public class AppUtil {
    private static AsyncHttpClient httpClient;


    static {

        httpClient = new AsyncHttpClient();
    }

    private static Gson gson;

    public static void getFile(Context context,String url,ResponseHandlerInterface responseHandler){

        httpClient.get(context,url,responseHandler);
    }


    public static void loadImage(final ImageView imageView,String url, final String tag){

        imageView.setTag(tag);
        httpClient.get(url,new BinaryHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] binaryData) {


                BitmapFactory.Options opts = new BitmapFactory.Options();
                opts.outHeight = 50;
                opts.outWidth = 50;

                Bitmap bitmap = BitmapFactory.decodeByteArray(binaryData, 0, binaryData.length,opts);
                if(tag.equals(imageView.getTag())){

                    imageView.setImageBitmap(bitmap);
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] binaryData, Throwable error) {

            }
        });

    }

    /**
     * parse json to bean
     * @param str
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T fromJson(String str, Class<T> clazz){
        if(TextUtils.isEmpty(str)){
            return null;
        }

        if (gson == null) {
            gson = new Gson();
        }
        return gson.fromJson(str, clazz);
    }

}
